import java.util.Arrays;

public class TestHeap {
    public int[] elem;
    public int UsedSize;

    public TestHeap() {
        this.elem = new int[10];
    }

    public void inti(int[] array) {
        for (int i = 0; i < array.length; i++) {
            elem[i] = array[i];
            UsedSize++;
        }
    }

    //将堆中的数据调整为大根堆
    public void createHeap() {
        for (int parent = (UsedSize - 1 - 1) / 2; parent >= 0; parent--) {
            siftDown(parent, UsedSize);
        }
    }

    //左右孩子的最大值跟根节点比较，比根节点大则交换
    private void swap(int i, int j) {
        int temp = elem[i];
        elem[i] = elem[j];
        elem[j] = temp;
    }

    public void siftDown(int parent, int end) {
        int child = 2 * parent + 1;
        while (child < end) {
            //防止数组越界
            if (child + 1 < end && elem[child] < elem[child + 1]) {
                child++;
            }
            //child下标就是左右孩子的最大值
            if (elem[child] > elem[parent]) {
                swap(child, parent);
                parent = child;
                child = 2 * parent + 1;
            } else {
                break;
            }
        }
    }

    //插入元素
    public void offer(int val){
        if(isFull()){
            //满了则进行扩容
            elem= Arrays.copyOf(elem,2*elem.length);
        }
        elem[UsedSize]=val;
        UsedSize++;
        //向上调整
        shitUp(UsedSize-1);
    }

    public void shitUp(int child){
        int parent =(child-1)/2;
        while(parent>=0){
            if(elem[child]>elem[parent]){
                swap(child,parent);
                child=parent;
                parent=(child-1)/2;
            }else {
                break;
            }
        }
    }

    //判断空间是否满了
    public boolean isFull(){
        return UsedSize== elem.length;
    }

    //删除元素
    public int poll(){
        if(isEmpty()){
            return -1;
        }
        int old=elem[0];
        swap(0,UsedSize-1);
        UsedSize--;
        siftDown(0,UsedSize);
        return old;
    }
    public boolean isEmpty(){
        return UsedSize==0;
    }

    //进行堆排序
    public void headSort(){
        int endIndex = UsedSize-1;
        while(endIndex>0){
            swap(0,endIndex);
            siftDown(0,endIndex);
            endIndex--;
        }
    }
}
